package com.kongjs.common.mybatis.plugins;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.kongjs.common.mybatis.enums.TenantIdType;
import com.kongjs.common.mybatis.properties.PluginProperties;
import com.kongjs.common.mybatis.properties.TenantProperties;
import com.kongjs.common.mybatis.tenant.TenantContextHolder;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.schema.Column;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;

@Component
public class TenantPlugin implements TenantLineHandler {
    private final TenantProperties tenantProperties;

    public TenantPlugin(PluginProperties pluginProperties) {
        this.tenantProperties = pluginProperties.getTenant();
    }

    @Override
    public Expression getTenantId() {
        String tenantId = TenantContextHolder.getTenantId();
        if (StringUtils.hasText(tenantId)) {
            if (TenantIdType.LONG.equals(tenantProperties.getTenantIdType())) {
                return new LongValue(tenantId);
            }
            if (TenantIdType.STRING.equals(tenantProperties.getTenantIdType())) {
                return new StringValue(tenantId);
            }
        }
        return new NullValue();
    }

    @Override
    public String getTenantIdColumn() {
        return tenantProperties.getTenantIdColumn();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        boolean ignore = TenantContextHolder.getIgnore();
        if (ignore) {
            return true;
        }
        Set<String> tenantTables = tenantProperties.getTenantTables();
        Set<String> ignoreTables = tenantProperties.getIgnoreTables();
        if (!CollectionUtils.isEmpty(tenantTables)) {
            return !tenantTables.contains(tableName);
        }
        if (!CollectionUtils.isEmpty(ignoreTables)) {
            return ignoreTables.contains(tableName);
        }
        return true;
    }

    @Override
    public boolean ignoreInsert(List<Column> columns, String tenantIdColumn) {
        return TenantLineHandler.super.ignoreInsert(columns, tenantIdColumn);
    }
}
